package com.maibow.controller.admin;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.entity.admin.Module;
import com.maibow.entity.admin.Organ;
import com.maibow.entity.admin.Role;
import com.maibow.entity.admin.SysOperator;
import com.maibow.service.admin.NewRoleService;
import com.maibow.service.admin.NewUserService;
import com.maibow.service.organ.OrganService;
import com.maibow.service.system.CommonService;
import com.maibow.util.AppUtil;
import com.maibow.util.CommonConstants;
import com.maibow.util.DateUtil;
import com.maibow.util.FileDownload;
import com.maibow.util.FileUpload;
import com.maibow.util.GetPinyin;
import com.maibow.util.ObjectExcelRead;
import com.maibow.util.ObjectExcelView;
import com.maibow.util.PageData;
import com.maibow.util.PathUtil;
import com.maibow.util.Tools;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.admin
 * 文件名：NewUserController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年4月1日-下午3:21:28
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/newuser")
public class NewUserController extends BaseController {

    @Resource(name = "newuserService")
    private NewUserService userService;

    @Resource(name = "newroleService")
    private NewRoleService roleService;

    @Resource(name = "organService")
    private OrganService organService;

    @Resource(name = "commonService")
    private CommonService commonService;

    /**
     * 
     * listUsers(显示用户列表)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/listUsers")
    public ModelAndView listUsers(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        String path = this.getRequest().getContextPath();
        String basePath = this.getRequest().getScheme() + "://" + this.getRequest().getServerName() + ":" + this.getRequest().getServerPort() + path + "/";

        SysOperator operator = commonService.getCurrentOperator();
        if (null == operator) {
            modelView.setViewName(this.getRequest().getContextPath() + CommonConstants.MAIN_LOGIN);
        }

        pageData.put("currentselectorganid", operator.getOrganid());
        List<PageData> organTree = organService.queryAllOrganListLight(pageData);
        for (PageData organ : organTree) {
            if (organ.get("is_parent") == null || organ.get("is_parent").toString().equals("1")) {
                organ.put("open", true);
            }
            organ.put("file", basePath + "/newuser/listUsersData");
        }

        JSONArray arr = JSONArray.fromObject(organTree);
        String json = arr.toString();
        json = json.replaceAll("organ_name", "name");
        modelView.setViewName("system/user/newuser_list");
        modelView.addObject("currentselectorganid", operator.getOrganid());
        modelView.addObject("zTreeNodes", json);
        modelView.addObject("pageData", pageData);
        return modelView;
    }

    /**
     * 
     * listUsersData(显示用户列表)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/listUsersData")
    public ModelAndView listUsersData(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();

        String username = pageData.getString("username");

        if (null != username && !"".equals(username)) {
            username = username.trim();
            pageData.put("username", username);
        }

        String lastloginbegin = pageData.getString("lastloginbegin");
        String lastloginend = pageData.getString("lastloginend");

        if (lastloginbegin != null && !"".equals(lastloginbegin)) {
            lastloginbegin = lastloginbegin + " 00:00:00";
            pageData.put("lastloginbegin", lastloginbegin);
        }
        if (lastloginend != null && !"".equals(lastloginend)) {
            lastloginend = lastloginend + " 00:00:00";
            pageData.put("lastloginend", lastloginend);
        }

        // String roleid =
        // pageData.getString("roleid");
        if (null != pageData.get("roleid") && !"".equals(pageData.get("roleid"))) {
            pageData.put("roleid", Integer.valueOf(pageData.get("roleid").toString()));
        }
        pageData.put("organid", Integer.valueOf(pageData.get("currentselectorganid").toString()));
        page.setPageData(pageData);

        // List<PageData> userList = null;
        // if (null == roleid ||
        // "".equals(roleid)) {
        // userList =
        // userService.querUserlistPageWithoutRole(page);
        // // 列出不包含角色的用户列表
        // } else {
        // userList =
        // userService.querUserlistPageWithinRole(page);
        // // 列出包含角色的用户列表
        // }
        List<PageData> userList = userService.querUserlistPageWithinRole(page);
        List<Role> roleList = roleService.listAllRoles(); // 列出所有二级角色

        for (PageData userPageData : userList) {
            PageData paramPageData = new PageData();
            paramPageData.put("organid", Integer.valueOf(userPageData.get("organid").toString()));
            paramPageData = organService.getOrganInfoById(paramPageData);
            userPageData.put("organname", paramPageData.get("organname"));

            if (null != userPageData.get("parentoperid")) {
                paramPageData.put("operid", Integer.valueOf(userPageData.get("parentoperid").toString()));
                paramPageData = userService.findByOperId(paramPageData);
                userPageData.put("parentopername", paramPageData.get("username"));
            }
        }

        PageData operPrivilegePageData = commonService.getOperPrivilege(CommonConstants.MODULE_URL_SYS_OPERATOR);

        SysOperator operator = commonService.getCurrentOperator();
        if (null == operator) {
            modelView.setViewName(this.getRequest().getContextPath() + CommonConstants.MAIN_LOGIN);
        }

        pageData.put("currentorganid", operator.getOrganid());
        
        modelView.setViewName("system/user/newuser_listdata");
        modelView.addObject("userList", userList);
        modelView.addObject("roleList", roleList);
        modelView.addObject("pageData", pageData);
        modelView.addObject("operPrivilegePageData", operPrivilegePageData);
        return modelView;
    }

    /**
     * 新增用户页面
     */
    @RequestMapping(value = "/goAddUser")
    public ModelAndView goAddUser() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        PageData paramPageData = new PageData();
        paramPageData.put("organid", Integer.valueOf(pageData.get("currentselectorganid").toString()));
        paramPageData = organService.getOrganInfoById(paramPageData);
        pageData.put("organname", paramPageData.get("organname"));
        List<Role> roleList = roleService.listAllRoles(); // 列出所有角色
        modelView.setViewName("system/user/newuser_add");
        modelView.addObject("pageData", pageData);
        modelView.addObject("roleList", roleList);
        return modelView;
    }

    /**
     * 保存添加的用户
     */
    @RequestMapping(value = "/saveUser")
    public ModelAndView saveUser(PrintWriter out) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        // PageData idPageData =
        // userService.findMaxOperId(pageData);
        // pageData.put("operid",
        // Integer.parseInt(idPageData == null ?
        // "0" : idPageData.get("mid").toString())
        // + 1); // ID
        SysOperator operator = commonService.getCurrentOperator();
        if (null == operator) {
            modelView.setViewName(this.getRequest().getContextPath() + CommonConstants.MAIN_LOGIN);
        }

        pageData.put("parentoperid", operator.getOperid());
        pageData.put("isadmin", "0");
        pageData.put("skin", "default"); // 默认皮肤
        pageData.put("password", new SimpleHash("SHA-1", pageData.getString("username"), pageData.getString("password")).toString());
        pageData.put("createtime", DateUtil.formatTime(DateUtil.getTime()));
        pageData.put("organid", Integer.valueOf(pageData.get("currentselectorganid").toString()));
        pageData.put("roleid", Integer.valueOf(pageData.get("roleid").toString()));
        pageData.put("createid", operator.getOperid());
        pageData.put("createname", operator.getUsername());

        // TODO 上级操作员从当登录的操作员信息里面取
        // pageData.put("parentoperid", 0);

        if (null == userService.findByUsername(pageData)) {
            userService.saveUser(pageData);
            modelView.addObject("msg", "success");
        } else {
            modelView.addObject("msg", "failed");
        }

        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 修改用户页面
     */
    @RequestMapping(value = "/goEditUser")
    public ModelAndView goEditUser() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();

        // 顶部修改个人资料
        String fx = pageData.getString("fx");

        if ("head".equals(fx)) {
            modelView.addObject("fx", "head");
        } else {
            modelView.addObject("fx", "user");
        }

        List<Role> roleList = roleService.listAllRoles(); // 列出所有二级角色
        pageData.put("operid", Integer.valueOf(pageData.get("operid").toString()));
        pageData = userService.findByOperId(pageData); // 根据ID读取
        PageData paramPageData = new PageData();
        paramPageData.put("organid", Integer.valueOf(pageData.get("organid").toString()));
        paramPageData = organService.getOrganInfoById(paramPageData);
        pageData.put("organname", paramPageData.get("organname"));
        pageData.put("currentselectorganid", pageData.get("organid"));
        modelView.setViewName("system/user/newuser_edit");
        modelView.addObject("pageData", pageData);
        modelView.addObject("roleList", roleList);

        return modelView;
    }

    /**
     * 保存修改的用户
     */
    @RequestMapping(value = "/editUser")
    public ModelAndView editUser(PrintWriter out) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        pageData.put("updatetime", DateUtil.formatTime(DateUtil.getTime()));
        if (pageData.getString("password") != null && !"".equals(pageData.getString("password"))) {
            pageData.put("password", new SimpleHash("SHA-1", pageData.getString("username"), pageData.getString("password")).toString());
        }

        pageData.put("operid", Integer.valueOf(pageData.get("operid").toString()));
        userService.editUser(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 修改用户页面
     */
    @RequestMapping(value = "/goEditUserPassword")
    public ModelAndView goEditUserPassword() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        pageData.put("operid", Integer.valueOf(pageData.get("operid").toString()));
        pageData = userService.findByOperId(pageData); // 根据ID读取
        PageData paramPageData = new PageData();
        paramPageData.put("organid", Integer.valueOf(pageData.get("organid").toString()));
        paramPageData = organService.getOrganInfoById(paramPageData);
        pageData.put("organname", paramPageData.get("organname"));
        pageData.put("currentselectorganid", pageData.get("organid"));
        modelView.setViewName("system/user/newuser_edit_password");
        modelView.addObject("pageData", pageData);
        return modelView;
    }

    /**
     * 保存修改的用户
     */
    @RequestMapping(value = "/editUserPassword")
    public ModelAndView editUserPassword(PrintWriter out) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        pageData.put("updatetime", DateUtil.formatTime(DateUtil.getTime()));
        pageData.put("password", new SimpleHash("SHA-1", pageData.getString("username"), pageData.getString("password")).toString());

        pageData.put("operid", Integer.valueOf(pageData.get("operid").toString()));
        userService.editUserPassword(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 判断用户名是否存在
     */
    @RequestMapping(value = "/hasUserName")
    public void hasUserName(PrintWriter out) {
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            if (userService.findByUsername(pageData) != null) {
                out.write("error");
            } else {
                out.write("success");
            }

            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 判断邮箱是否存在
     */
    @RequestMapping(value = "/hasEmail")
    public void hasEmail(PrintWriter out) {
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();

            if (pageData.get("email") == null || "".equals(pageData.get("email").toString())) {
                out.write("success");
            } else {
                if (userService.findByEmail(pageData) != null) {
                    out.write("error");
                } else {
                    out.write("success");
                }
            }
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/deleteUser")
    public void deleteUser(PrintWriter out) {
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            pageData.put("operid", Integer.valueOf(pageData.get("operid").toString()));
            userService.deleteUser(pageData);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAllUser")
    @ResponseBody
    public Object deleteAllUser() {
        PageData pageData = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pageData = this.getPageData();
            List<PageData> pagedataList = new ArrayList<PageData>();
            String operids = pageData.getString("operids");

            if (null != operids && !"".equals(operids)) {
                String ArrayUSER_IDS[] = operids.split(",");
                Number[] num = new Number[ArrayUSER_IDS.length];
                int i = 0;
                for (String str : ArrayUSER_IDS) {
                    num[i] = Integer.valueOf(str);
                    i++;
                }
                userService.deleteAllUser(num);
                pageData.put("msg", "ok");
            } else {
                pageData.put("msg", "no");
            }

            pagedataList.add(pageData);
            map.put("list", pagedataList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pageData, map);
    }

    // ===================================================================================================

    /*
     * 导出用户信息到EXCEL
     * @return
     */
    @RequestMapping(value = "/exportExcel")
    public ModelAndView exportExcel() {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        try {

            // 检索条件===
            String username = pageData.getString("username");
            if (null != username && !"".equals(username)) {
                username = username.trim();
                pageData.put("username", username);
            }
            String lastloginbegin = pageData.getString("lastloginbegin");
            String lastloginend = pageData.getString("lastloginend");
            if (lastloginbegin != null && !"".equals(lastloginbegin)) {
                lastloginbegin = lastloginbegin + " 00:00:00";
                pageData.put("lastloginbegin", lastloginbegin);
            }
            if (lastloginend != null && !"".equals(lastloginend)) {
                lastloginend = lastloginend + " 00:00:00";
                pageData.put("lastloginend", lastloginend);
            }
            // 检索条件===

            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();

            titles.add("用户名"); // 1
            titles.add("姓名"); // 2
            titles.add("电话号码"); // 3
            titles.add("角色"); // 4
            titles.add("上级操作员"); // 5
            titles.add("邮箱"); // 6
            titles.add("最近登录"); // 7
            titles.add("创建时间"); // 8
            titles.add("解锁时间"); // 9
            titles.add("上次登录IP");// 10
            titles.add("状态"); // 11

            dataMap.put("titles", titles);

            // String roleid =
            // pageData.getString("roleid");
            //
            // List<PageData> userList = null;
            // if (null == roleid ||
            // "".equals(roleid)) {
            // userList =
            // userService.querUserlistPageWithoutRolePageData(pageData);
            // // 列出不包含角色的用户列表
            // } else {
            // userList =
            // userService.querUserlistPageWithinRolePageData(pageData);
            // // 列出包含角色的用户列表
            // }
            List<PageData> userList = userService.querUserlistWithinRolePageData(pageData);

            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < userList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", userList.get(i).getString("username")); // 1
                vpd.put("var2", userList.get(i).getString("nickname")); // 2
                vpd.put("var3", userList.get(i).getBigDecimal("phonenumber").toString()); // 3
                vpd.put("var4", userList.get(i).getString("roleName")); // 4
                vpd.put("var5", userList.get(i).getString("parentopername")); // 5
                vpd.put("var6", userList.get(i).getString("email")); // 6
                vpd.put("var7", userList.get(i).getDateString("logintime")); // 7
                vpd.put("var8", userList.get(i).getDateString("createtime"));
                vpd.put("var9", userList.get(i).getDateString("unlocktime"));
                vpd.put("var10", userList.get(i).getString("loginip"));
                if (userList.get(i).getString("isvalid").equals("1")) {
                    vpd.put("var11", "正常");
                } else {
                    vpd.put("var11", "冻洁");
                }
                varList.add(vpd);
            }

            dataMap.put("varList", varList);

            ObjectExcelView erv = new ObjectExcelView(); // 执行excel操作

            modelView = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 打开上传EXCEL页面
     */
    @RequestMapping(value = "/importExcel")
    public ModelAndView goUploadExcel() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        modelView.setViewName("system/user/newuploadExcel");
        return modelView;
    }

    /**
     * 下载模版
     */
    @RequestMapping(value = "/downloadExcel")
    public void downExcel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, PathUtil.getClasspath() + CommonConstants.FILEPATHFILE + "Users.xls", "Users.xls");
    }

    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value = "/readExcel")
    public ModelAndView readExcel(@RequestParam(value = "excel", required = false) MultipartFile file) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();

        if (null != file && !file.isEmpty()) {
            String filePath = PathUtil.getClasspath() + CommonConstants.FILEPATHFILE; // 文件上传路径
            String fileName = FileUpload.fileUp(file, filePath, "userexcel"); // 执行上传

            // 执行读EXCEL操作,读出的数据导入List
            // 2:从第3行开始；0:从第A列开始；0:第0个sheet
            List<PageData> listPagedata = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);

            for (int i = 0; i < listPagedata.size(); i++) {
                PageData idPageData = userService.findMaxOperId(pageData);
                pageData.put("operid", Integer.parseInt(idPageData == null ? "0" : idPageData.get("mid").toString()) + 1); // ID
                pageData.put("isadmin", "0");
                pageData.put("skin", "default"); // 默认皮肤
                pageData.put("createtime", DateUtil.formatTime(DateUtil.getTime()));

                String username = GetPinyin.getPingYin(listPagedata.get(i).getString("var0")); // 根据姓名汉字生成全拼
                pageData.put("username", username);
                if (userService.findByUsername(pageData) != null) { // 判断用户名是否重复
                    username = GetPinyin.getPingYin(listPagedata.get(i).getString("var0")) + Tools.getRandomNum();
                    pageData.put("username", username);
                }

                pageData.put("nickname", listPagedata.get(i).getString("var1"));
                pageData.put("phonenumber", listPagedata.get(i).getString("var2"));
                pageData.put("roleid", Integer.valueOf(listPagedata.get(i).getString("var3")));
                pageData.put("parentoperid", Integer.valueOf(listPagedata.get(i).getString("var4")));
                if (Tools.checkEmail(listPagedata.get(i).getString("var5"))) { // 邮箱格式不对就跳过
                    pageData.put("email", listPagedata.get(i).getString("var5"));
                    if (userService.findByEmail(pageData) != null) { // 邮箱已存在就跳过
                        continue;
                    }
                } else {
                    continue;
                }
                pageData.put("isvalid", listPagedata.get(i).getString("var6")); // 状态
                pageData.put("password", new SimpleHash("SHA-1", username, "12356").toString());// 默认密码123
                userService.saveUser(pageData);
            }

            modelView.addObject("msg", "success");
        }

        modelView.setViewName("save_result");
        return modelView;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }

    /*
     * ===============================权限============
     * ======================
     */
    public void getHC() {
        ModelAndView modelView = this.getModelAndView();
        // shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        List<Module> menuList = (List) session.getAttribute(CommonConstants.SESSION_MODULE_LIST);
        modelView.addObject(CommonConstants.SESSION_MODULE_LIST, menuList);// 菜单权限
    }
    /*
     * ===============================权限============
     * ======================
     */
}
